package com.lee.exception;

import com.lee.properties.StatusConstants;
import com.lee.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;
import java.sql.SQLException;
import java.util.stream.Collectors;

/**
 * @aithour Lee HN
 * @date 2019/6/6
 * 全局Exception
 **/
@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {

    public static final String EXP_MSG = "系统维护，请稍后再试";

    @ExceptionHandler(BindException.class)
    public ResponseVO bindException(BindException exception) {
        final String message = exception.getBindingResult().getAllErrors().stream().map(ObjectError::getDefaultMessage).
                collect(Collectors.joining(","));
        return ResponseVO.failure(StatusConstants.BAD_DATA_TYPE, message);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseVO illegalArgumentException(IllegalArgumentException exception) {
        return ResponseVO.failure(StatusConstants.BAD_DATA_TYPE, exception.getMessage());
    }

    @ExceptionHandler(IllegalStateException.class)
    public ResponseVO illegalStateException(IllegalStateException exception) {
        return ResponseVO.failure(StatusConstants.BAD_STATUS, exception.getMessage());
    }

    @ExceptionHandler(UnsupportedOperationException.class)
    public ResponseVO unsupportedOperationException(UnsupportedOperationException exception) {
        return ResponseVO.failure(StatusConstants.BAD_OPERATION, exception.getMessage());
    }

    @ExceptionHandler(IOException.class)
    public ResponseVO ioException(IOException exception) {
        exception.printStackTrace();
        return ResponseVO.failure(StatusConstants.SERVER_ERROR, EXP_MSG);
    }

    @ExceptionHandler(AuthenticationException.class)
    public ResponseVO authenticationException(AuthenticationException exception) {
        throw exception;
    }

    @ExceptionHandler(AccessDeniedException.class)
    public ResponseVO accessDeniedException(AccessDeniedException exception) {
        throw exception;
    }

    @ExceptionHandler(RuntimeException.class)
    public ResponseVO runtimeException(RuntimeException exception) {
        exception.printStackTrace();
        return ResponseVO.failure(StatusConstants.SERVER_ERROR, EXP_MSG);
    }

    @ExceptionHandler(SQLException.class)
    public ResponseVO sqlException(SQLException exception) {
        exception.printStackTrace();
        return ResponseVO.failure(StatusConstants.SERVER_ERROR, EXP_MSG);
    }

}

